$(function() {
    $('.sendmsg').on('click', function() {
        let text = $('.talk').val().trim();
        if (text.length <= 0) {
            return $('.talk').val('')
        }
        $('.chat-body ul').append('<li class="man"><div class="img-box1"><img src="./img/person03.jpg" alt=""></div><div class="chat-content"><img src="./img/corner02.png" alt=""><span>' + text + '</span></div></li>');
        $('.talk').val('');
        getMassage(text)
        resetUi()
    })
    $(window).on('keydown', function(e) {
        if (e.key === 'Enter') {

            $('.sendmsg').click();

        }
    })


    function resetUi() {
        let bigheight = $(document).innerHeight() * 0.66;
        if ($('.chat-body ul').innerHeight() >= bigheight) {
            $('.chat-body').scrollTop($('.chat-body ul').innerHeight() - bigheight + 330);
        }

    }

    // function getVoice(text) {
    //     $.ajax({
    //         type: 'get',
    //         url: 'http://www.liulongbin.top:3006/api/synthesize',
    //         data: {
    //             text: text
    //         },
    //         success: function(res) {
    //             if (res.message === 'success') {
    //                 $('.chat-body ul').find('audio').attr('src', res.voiceUrl)
    //             }
    //         }
    //     })
    // }

    function getMassage(text) {
        const data = {
            "model": "text-davinci-003",
            "max_tokens": 4000,
            "top_p": 1,
            "temperature": 0.5,
            "frequency_penalty": 0,
            "presence_penalty": 0,
            "prompt": text
        }
        $.ajax({
            type: 'post',
            url: 'https://api.openai.com/v1/completions',
            headers: {
                'Authorization': 'Bearer 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',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data: JSON.stringify(data),
            dataType: "json",
            success: function(res) {
                if (res.id !== null) {
                    let msg = res.choices[0].text;
                    console.log(msg);
                    $('.chat-body ul').append('<li class="woman"><div class="img-box1"><img src="./img/科隆同学.jpg" alt=""></div><div class="chat-content"><img src="./img/corner01.png" alt=""><span>' + msg + '</span></div></li>');
                    resetUi()
                        // getVoice(msg)
                } else {
                    console.log(res.choices[0].text);
                }
            }
        })
    }



})